package com.centaline.androidsalesblog.widgets.vpinfinite;

import android.content.Context;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Interpolator;
import android.widget.RelativeLayout;

import com.centaline.androidsalesblog.R;

import java.lang.reflect.Field;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 循环播放ViewPager
 *
 * @author GL
 */
public class SliderLayoutEx extends RelativeLayout {

    private InfiniteViewPager mViewPager;

    private PagerAdapter mPagerAdapter;

    // 重启循环
    private Timer mResumingTimer;
    private TimerTask mResumingTask;

    // 循环
    private Timer mCycleTimer;
    private TimerTask mCycleTask;

    /**
     * 循环间隔
     */
    private long mSliderDuration = 6000;

    /**
     * 切换时间
     */
    private int mTransformerSpan = 1500;

    private boolean mCycling;

    public SliderLayoutEx(Context context) {
        this(context, null);
    }

    public SliderLayoutEx(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SliderLayoutEx(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.isInEditMode();
        LayoutInflater.from(context).inflate(R.layout.layout_swipe_viewpager, this,
                true);

        mViewPager = (InfiniteViewPager) findViewById(R.id.infiniteViewPager);
        mViewPager.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_UP:
                        recoverCycle();
                        break;
                }
                return false;
            }
        });
        setSliderTransformDuration(mTransformerSpan, null);
    }

    public void setPagerAdapter(PagerAdapter pagerAdapter) {
        mPagerAdapter = pagerAdapter;
        PagerAdapter wrappedAdapter = new InfinitePagerAdapter(mPagerAdapter);
        mViewPager.setAdapter(wrappedAdapter);
        startAutoCycle();
    }

    public void setOnPageChangeListener(
            ViewPagerEx.OnPageChangeListener onPageChangeListener) {
        if (onPageChangeListener != null) {
            mViewPager.setOnPageChangeListener(onPageChangeListener);
        }
    }

    public PagerAdapter getPagerAdapter() {
        return mPagerAdapter;
    }

    public int getRealCount() {
        if (mPagerAdapter != null) {
            return mPagerAdapter.getCount();
        } else {
            return 0;
        }
    }

    private android.os.Handler mh = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mViewPager.nextItem();
        }
    };

    /**
     * 手指按下，拦截触摸
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                pauseAutoCycle();
                break;
        }
        return false;
    }

    /**
     * 手指离开，重启循环
     */
    private void recoverCycle() {
        if (!mCycling) {
            if (mResumingTask != null && mResumingTimer != null) {
                mResumingTimer.cancel();
                mResumingTask.cancel();
            }
            mResumingTimer = new Timer();
            mResumingTask = new TimerTask() {
                @Override
                public void run() {
                    startAutoCycle();
                }
            };
            mResumingTimer.schedule(mResumingTask, 5000);
        }
    }

    /**
     * 开始循环
     */
    public void startAutoCycle() {
        startAutoCycle(3000, mSliderDuration);
    }

    /**
     * 暂停循环
     */
    public void pauseAutoCycle() {
        if (mCycling) {
            mCycleTimer.cancel();
            mCycleTask.cancel();
            mCycling = false;
        } else {
            if (mResumingTimer != null && mResumingTask != null) {
                recoverCycle();
            }
        }
    }

    /**
     * 开始自动循环
     */
    public void startAutoCycle(long delay, long duration) {
        if (mCycleTimer != null)
            mCycleTimer.cancel();
        if (mCycleTask != null)
            mCycleTask.cancel();
        mSliderDuration = duration;
        mCycleTimer = new Timer();
        mCycleTask = new TimerTask() {
            @Override
            public void run() {
                mh.sendEmptyMessage(0);
            }
        };
        mCycleTimer.schedule(mCycleTask, delay, mSliderDuration);
        mCycling = true;
    }

    /**
     * 设置切换时间
     */
    private void setSliderTransformDuration(int period,
                                            Interpolator interpolator) {
        try {
            Field mScroller = ViewPagerEx.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true);
            FixedSpeedScroller scroller = new FixedSpeedScroller(
                    mViewPager.getContext(), interpolator, period);
            mScroller.set(mViewPager, scroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
